const express = require('express');const router = express.Router();const activityService = require('../services/activityService');const { authenticate, isAdmin } = require('../middlewares/authMiddleware');const userService = require('../services/userService');const logger = require('../utils/logger');

// 中间件 - 检查管理员权限
const checkAdminRole = async (req, res, next) => {
  if (req.user && req.user.role === 'admin') {
    return next();
  }
  return res.status(403).json({ 
    success: false,
    message: '需要管理员权限',
    code: 'PERMISSION_DENIED'
  });
};

// 参数验证中间件
const validateParams = (schema) => {
  return (req, res, next) => {
    const validationResults = schema(req);
    if (validationResults.error) {
      return res.status(400).json({
        success: false,
        message: '参数验证失败',
        errors: validationResults.error,
        code: 'INVALID_PARAMS'
      });
    }
    next();
  };
};

// 参数验证模式
const validationSchemas = {
  activeTime: (req) => {
    const { seconds, sessionId } = req.body;
    const errors = [];
    
    if (!seconds) errors.push('缺少seconds参数');
    else if (isNaN(seconds) || seconds <= 0) errors.push('seconds必须是大于0的数字');
    
    if (!sessionId) errors.push('缺少sessionId参数');
    
    return errors.length > 0 ? { error: errors } : { error: null };
  },
  
  messageSent: (req) => {
    const { contactId } = req.body;
    const errors = [];
    
    if (!contactId) errors.push('缺少contactId参数');
    
    return errors.length > 0 ? { error: errors } : { error: null };
  },
  
  session: (req) => {
    const { sessionToken } = req.body;
    const errors = [];
    
    if (!sessionToken) errors.push('缺少sessionToken参数');
    
    return errors.length > 0 ? { error: errors } : { error: null };
  },
  
  endSession: (req) => {
    const { sessionId } = req.body;
    const errors = [];
    
    if (!sessionId) errors.push('缺少sessionId参数');
    
    return errors.length > 0 ? { error: errors } : { error: null };
  },
  
  whatsappSession: (req) => {
    const { sessionId, phoneNumber } = req.body;
    const errors = [];
    
    if (!sessionId) errors.push('缺少sessionId参数');
    
    return errors.length > 0 ? { error: errors } : { error: null };
  }
};

// 全局错误处理器
const asyncHandler = (fn) => (req, res, next) => {
  Promise.resolve(fn(req, res, next)).catch((error) => {
    logger.error(`API错误: ${req.method} ${req.originalUrl}`, error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined,
      code: 'SERVER_ERROR'
    });
  });
};

// 更新用户活跃时间
router.post('/active-time', 
  authenticate, 
  validateParams(validationSchemas.activeTime),
  asyncHandler(async (req, res) => {
    const { seconds, sessionId } = req.body;
    const userId = req.user.id;

    const result = await activityService.updateActiveTime(userId, sessionId, seconds);
    res.json(result);
  })
);

// 记录消息发送
router.post('/message-sent', 
  authenticate, 
  validateParams(validationSchemas.messageSent),
  asyncHandler(async (req, res) => {
    const { contactId } = req.body;
    const userId = req.user.id;

    const result = await activityService.recordMessageSent(userId, contactId);
    res.json(result);
  })
);

// 获取用户当日活跃度
router.get('/daily', 
  authenticate, 
  asyncHandler(async (req, res) => {
    const userId = req.user.id;
    const result = await activityService.getUserDailyActivity(userId);
    res.json(result);
  })
);

// 获取用户活跃度历史 (当前用户)
router.get('/history', 
  authenticate, 
  asyncHandler(async (req, res) => {
    const userId = req.user.id;
    const { startDate, endDate } = req.query;
    
    // 参数验证
    if (startDate && !(/^\d{4}-\d{2}-\d{2}$/.test(startDate))) {
      return res.status(400).json({
        success: false,
        message: 'startDate格式不正确，应为YYYY-MM-DD',
        code: 'INVALID_DATE_FORMAT'
      });
    }
    
    if (endDate && !(/^\d{4}-\d{2}-\d{2}$/.test(endDate))) {
      return res.status(400).json({
        success: false,
        message: 'endDate格式不正确，应为YYYY-MM-DD',
        code: 'INVALID_DATE_FORMAT'
      });
    }
    
    const result = await activityService.getUserActivityHistory(userId, startDate, endDate);
    res.json(result);
  })
);

// 获取用户活跃度报告 (当前用户)
router.get('/report', 
  authenticate, 
  asyncHandler(async (req, res) => {
    const userId = req.user.id;
    const { period } = req.query;
    
    // 参数验证
    const validPeriods = ['day', 'week', 'month', 'custom'];
    if (period && !validPeriods.includes(period)) {
      return res.status(400).json({
        success: false,
        message: `period必须是以下值之一: ${validPeriods.join(', ')}`,
        code: 'INVALID_PERIOD'
      });
    }
    
    const result = await activityService.getUserActivityReport(userId, period);
    res.json(result);
  })
);

// === 管理员 API ===

// 获取所有用户的活跃度统计 (仅管理员)
router.get('/all', 
  authenticate, 
  checkAdminRole, 
  asyncHandler(async (req, res) => {
    const { date } = req.query;
    
    // 参数验证
    if (date && !(/^\d{4}-\d{2}-\d{2}$/.test(date))) {
      return res.status(400).json({
        success: false,
        message: 'date格式不正确，应为YYYY-MM-DD',
        code: 'INVALID_DATE_FORMAT'
      });
    }
    
    const result = await activityService.getAllUsersActivity(date);
    res.json(result);
  })
);

// 获取所有用户的活跃度报告 (仅管理员)
router.get('/all/report', 
  authenticate, 
  checkAdminRole, 
  asyncHandler(async (req, res) => {
    const { period } = req.query;
    
    // 参数验证
    const validPeriods = ['day', 'week', 'month', 'custom'];
    if (period && !validPeriods.includes(period)) {
      return res.status(400).json({
        success: false,
        message: `period必须是以下值之一: ${validPeriods.join(', ')}`,
        code: 'INVALID_PERIOD'
      });
    }
    
    const result = await activityService.getAllUsersActivityReport(period);
    res.json(result);
  })
);

// 获取特定用户的活跃度报告 (仅管理员)
router.get('/user/:userId/report', 
  authenticate, 
  checkAdminRole, 
  asyncHandler(async (req, res) => {
    const { userId } = req.params;
    const { period } = req.query;
    
    // 参数验证
    if (isNaN(userId)) {
      return res.status(400).json({
        success: false, 
        message: 'userId必须是数字',
        code: 'INVALID_USER_ID'
      });
    }
    
    const validPeriods = ['day', 'week', 'month', 'custom'];
    if (period && !validPeriods.includes(period)) {
      return res.status(400).json({
        success: false,
        message: `period必须是以下值之一: ${validPeriods.join(', ')}`,
        code: 'INVALID_PERIOD'
      });
    }
    
    // 验证用户存在
    const userExists = await userService.getUserById(userId);
    if (!userExists) {
      return res.status(404).json({
        success: false, 
        message: '用户不存在',
        code: 'USER_NOT_FOUND'
      });
    }
    
    const result = await activityService.getUserActivityReport(userId, period);
    res.json(result);
  })
);

// 获取特定用户的活跃度历史 (仅管理员)
router.get('/user/:userId/history', 
  authenticate, 
  checkAdminRole, 
  asyncHandler(async (req, res) => {
    const { userId } = req.params;
    const { startDate, endDate } = req.query;
    
    // 参数验证
    if (isNaN(userId)) {
      return res.status(400).json({
        success: false, 
        message: 'userId必须是数字',
        code: 'INVALID_USER_ID'
      });
    }
    
    if (startDate && !(/^\d{4}-\d{2}-\d{2}$/.test(startDate))) {
      return res.status(400).json({
        success: false,
        message: 'startDate格式不正确，应为YYYY-MM-DD',
        code: 'INVALID_DATE_FORMAT'
      });
    }
    
    if (endDate && !(/^\d{4}-\d{2}-\d{2}$/.test(endDate))) {
      return res.status(400).json({
        success: false,
        message: 'endDate格式不正确，应为YYYY-MM-DD',
        code: 'INVALID_DATE_FORMAT'
      });
    }
    
    // 验证用户存在
    const userExists = await userService.getUserById(userId);
    if (!userExists) {
      return res.status(404).json({
        success: false, 
        message: '用户不存在',
        code: 'USER_NOT_FOUND'
      });
    }
    
    const result = await activityService.getUserActivityHistory(userId, startDate, endDate);
    res.json(result);
  })
);

// 创建用户会话
router.post('/session/start', 
  authenticate, 
  validateParams(validationSchemas.session),
  asyncHandler(async (req, res) => {
    const userId = req.user.id;
    const { sessionToken } = req.body;
    const ipAddress = req.ip;
    const userAgent = req.headers['user-agent'];
    
    const result = await activityService.createUserSession(
      userId, 
      sessionToken || req.sessionID, 
      ipAddress, 
      userAgent
    );
    
    res.json({
      success: true,
      sessionId: result.id
    });
  })
);

// 结束用户会话
router.post('/session/end', 
  authenticate, 
  validateParams(validationSchemas.endSession),
  asyncHandler(async (req, res) => {
    const { sessionId, reason } = req.body;
    
    const result = await activityService.endUserSession(sessionId, reason);
    res.json({
      success: true,
      endTime: result.endTime,
      duration: result.duration
    });
  })
);

// 记录WhatsApp会话开始
router.post('/whatsapp/session/start', 
  authenticate, 
  validateParams(validationSchemas.whatsappSession),
  asyncHandler(async (req, res) => {
    const userId = req.user.id;
    const { sessionId, phoneNumber } = req.body;
    
    const result = await activityService.recordWhatsAppSessionStart(
      userId, 
      sessionId, 
      phoneNumber
    );
    
    res.json({
      success: true,
      sessionId: result.id
    });
  })
);

// 记录WhatsApp会话结束
router.post('/whatsapp/session/end', 
  authenticate, 
  validateParams(validationSchemas.endSession),
  asyncHandler(async (req, res) => {
    const { sessionId } = req.body;
    
    const result = await activityService.recordWhatsAppSessionEnd(sessionId);
    res.json({
      success: true,
      endTime: result.endTime,
      duration: result.duration
    });
  })
);

module.exports = router; 